package com.yeskery.nut.bean.condition;

import com.yeskery.nut.annotation.condition.ConditionalOnServerType;
import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.application.ServerType;
import com.yeskery.nut.scan.BeanAnnotationScanMetadata;
import com.yeskery.nut.util.ServerUtils;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 服务类型条件判断
 * @author sunjay
 * 2023/9/6
 */
public class OnServerTypeCondition implements Condition {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(OnServerTypeCondition.class.getName());

    @Override
    public boolean matches(NutApplication nutApplication, Collection<BeanAnnotationScanMetadata> beanAnnotationScanMetadata, Object conditionalAnnotation) {
        ConditionalOnServerType conditionalOnServerType = (ConditionalOnServerType) conditionalAnnotation;
        boolean result = doMatches(nutApplication, conditionalOnServerType.value());
        if (!result && logger.isLoggable(Level.FINEST)) {
            logger.log(Level.FINEST, "ServerType Condition Not Match, Condition[" + this.getClass().getName()
                    + "], Expect ServerType[" + conditionalOnServerType.value().name()
                    + "], Actual ServerType[" + nutApplication.getApplicationMetadata().getServerType().name() + "]");
        }
        return result;
    }

    /**
     * 判断bean是否匹配的方法
     * @param nutApplication Nut应用对象
     * @param serverType 服务类型
     * @return bean是否匹配的方法
     */
    protected boolean doMatches (NutApplication nutApplication, ServerType serverType) {
        return ServerUtils.getServerType(nutApplication.getBasicConfigure()) == serverType;
    }
}
